package com.boot.sample.websocket.adapter;

import com.boot.sample.websocket.dbo.User;
import com.boot.sample.websocket.dbo.WebUser;
import com.boot.sample.websocket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class UserSessionAdapter {

    private static Map<String, String> userSessionIdMap=new HashMap<>();

    private static Map<String, WebSocketSession> sessionMap=new HashMap<>();

    private static Map<String, String> sessionUserMap=new HashMap<>();

    @Autowired
    private UserService userService;

    public void userOnline(WebSocketSession session,String uid){
        sessionMap.put(session.getId(),session);
        userSessionIdMap.put(uid,session.getId());
        sessionUserMap.put(session.getId(),uid);
    }

    public void userOffline(WebSocketSession session){
        sessionMap.remove(session.getId());
        if(sessionUserMap.containsKey(session.getId())){
            String uid= sessionUserMap.get(session.getId());
            userSessionIdMap.remove(uid);
            sessionUserMap.remove(session.getId());
        }
    }


    public WebSocketSession getWebSocketSessionByUid(String uid){
        if(userSessionIdMap.containsKey(uid)){
            String sessionId= userSessionIdMap.get(uid);
            return sessionMap.get(sessionId);
        }
        return null;
    }

    public String getUserNameBySessionId(String sessionId){
        if(sessionUserMap.containsKey(sessionId)){
            String uid= sessionUserMap.get(sessionId);
            User user = userService.getUserByUid(uid);
            if(null != user){
                return user.getName();
            }
        }
        return null;
    }

}
